package com.sharing.library.controller;

import com.sharing.library.entity.BookType;
import com.sharing.library.repository.BookRepository;
import com.sharing.library.repository.BookTypeRepository;
import com.zhx.framework.util.result.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.web.bind.annotation.*;

/**
 * @author zhanghaixuan
 * @create 2018/3/17-下午2:03
 **/
@RestController
@RequestMapping("/booktype")
@Api(description="书种类")
public class BookTypeController {

    @Autowired
    private BookTypeRepository bookTypeRepository;

    @Autowired
    private BookRepository bookRepository;

    //获取全部书种类的列表

    @PostMapping("/getBookTypeList")
    @ApiOperation(value="获取全部书的种类", notes="获取全部书的种类")
    public Result getBookTypeList(Pageable pageable){
        Page<BookType> all = bookTypeRepository.findAll(pageable);

        return Result.OK("",all);
    }

    @PostMapping("/save")
    @ApiOperation(value="生成一个书种类", notes="生成一个书种类")
    public Result save(@RequestBody BookType bookType){
        BookType save = bookTypeRepository.save(bookType);

        return Result.OK("",save);
    }

    //详情
    @PostMapping("/detail")
    @ApiOperation(value="书种类详情", notes="书种类详情")
    public Result detail(@RequestParam Long id){
        BookType one = bookTypeRepository.findOne(id);

        return Result.OK("",one);
    }

    //详情
    @PostMapping("/delete")
    @ApiOperation(value="删除书的种类", notes="删除书的种类")
    public Result delete(@RequestParam Long id){

        int i = bookRepository.countByTypeId(Long.toString(id));

        if(i>0){
            return Result.Error(500,"当前类型以及被使用了");
        }

        bookTypeRepository.delete(id);

        return Result.OK("","删除成功");
    }

}
